<template>
  <div class="category-container">
    <!-- 加载状态 -->
    <el-skeleton v-if="loading" :rows="5" animated />
    
    <!-- 分类列表 -->
    <div v-else class="category-list">
      <el-row :gutter="20" justify="center">
        <el-col 
          v-for="(category, index) in categories" 
          :key="index" 
          :xs="12" 
          :sm="8" 
          :md="6" 
          :lg="4"
        >
          <div 
            class="category-card" 
            @click="navigateToCategory(category.typeId)"
          >
            <!-- 修复图片加载 -->
            <el-image 
              :src="getImageUrl(category.image)" 
              fit="cover" 
              class="category-image"
              :preview-src-list="[getImageUrl(category.image)]"
            >
              <!-- 图片加载失败的占位内容 -->
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
            
            <div class="category-overlay">
              <h3 class="category-title">{{ category.typeName || '未命名分类' }}</h3>
              <p class="category-desc">{{ category.typeDesc || '暂无描述' }}</p>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { Picture } from '@element-plus/icons-vue'
import { useCounterStore } from '@/stores/counter'

const router = useRouter()
const categories = ref([])
const loading = ref(true)
const useStore = useCounterStore()

// 页面加载时获取分类数据
onMounted(() => {
  getCategoryData()
})

// 获取分类数据
const getCategoryData = async () => {
  try {
    loading.value = true
    console.log("获取分类数据")
    const res = await axios.get('/advertisement/list')
    console.log("API响应:", res.data)
    
    // 处理返回数据，确保数据结构正确
    if (res.data && res.data.data && res.data.data.list) {
      categories.value = res.data.data.list.map(item => ({
        ...item,
        // 确保图片URL有效
        image: item.image || getDefaultImage(),
        path: item.path || `/category/${item.id || item.typeName}`
      }))
    } else {
      console.warn('API返回数据格式异常，使用默认数据')
      categories.value = getDefaultCategories()
    }
  } catch (error) {
    console.error("获取分类数据失败:", error)
    // 错误时使用默认数据
    categories.value = getDefaultCategories()
  } finally {
    loading.value = false
  }
}

// 处理图片URL
const getImageUrl = (imgUrl) => {
  if (!imgUrl) return getDefaultImage()
  
  // 如果是完整URL直接返回
  if (imgUrl.startsWith('http')) return imgUrl
  
  // 如果是相对路径，添加基础URL
  return `http://localhost:8080${imgUrl.startsWith('/') ? '' : '/'}${imgUrl}`
}

// 默认图片
const getDefaultImage = () => {
  return 'https://picsum.photos/300/200?random=' + Math.random()
}

// 默认分类数据（备用）
const getDefaultCategories = () => {
  return [
    {
      typeName: '工程机械',
      typeDesc: '用于工程建设、矿山开采等场景的重型机械',
      image: getDefaultImage(),
      path: '/category/engineering'
    },
    {
      typeName: '农业机械', 
      typeDesc: '用于农业耕种、收获、加工等场景的机械',
      image: getDefaultImage(),
      path: '/category/agriculture'
    },
    {
      typeName: '物流机械',
      typeDesc: '用于货物装卸、运输、仓储等场景的机械', 
      image: getDefaultImage(),
      path: '/category/logistics'
    }
  ]
}

// 导航到分类页面
const navigateToCategory = (path) => {
  console.log("导航到分类页面:", path)
  useStore.typeId = path
  console.log("导航到分类页面:", useStore.typeId)
  router.push('maiche')
  // if (path) {
  //   router.push(path)
  // }
}
</script>

<style scoped>
.category-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.category-list {
  margin-top: 20px;
}

.category-card {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.category-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.category-image {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #999;
  font-size: 14px;
}

.image-error .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
  color: #ccc;
}

.category-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  padding: 20px 15px;
  color: white;
}

.category-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 5px;
  line-height: 1.2;
}

.category-desc {
  font-size: 12px;
  opacity: 0.9;
  line-height: 1.4;
  margin: 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .category-container {
    padding: 15px 10px;
  }
  
  .category-image {
    height: 150px;
  }
  
  .category-overlay {
    padding: 15px 10px;
  }
  
  .category-title {
    font-size: 14px;
  }
  
  .category-desc {
    font-size: 11px;
  }
}
</style>